const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 获取当前环境模式
const mode = process.env.NODE_ENV || 'development';

// 公共配置
const commonConfig = {
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: ['ts-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        type: 'asset/resource',
        generator: {
          filename: 'assets/[name].[ext]'
        }
      }
    ]
  },
  devtool: mode === 'development' ? 'source-map' : false,
  optimization: {
    splitChunks: {
      chunks: 'all'
    },
    usedExports: true, // 启用tree shaking标记
    sideEffects: false // 默认所有文件都有副作用
  },
  // 统一的core-js配置
  plugins: [
    new webpack.ProvidePlugin({
      regeneratorRuntime: 'regenerator-runtime/runtime'
    })
  ],
};

// 主进程配置
const mainConfig = {
  ...commonConfig,
  mode: mode,
  entry: {
    main: ['./src/backend/main.ts'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  target: 'electron-main',
  node: {
    __dirname: false,
    __filename: false,
  },
  externals: {
    'electron': 'commonjs electron',
  },
  optimization: {
    ...commonConfig.optimization,
    sideEffects: false
  }
};

// 预加载脚本配置
const preloadConfig = {
  ...commonConfig,
  mode: mode,
  entry: {
    preload: ['./src/backend/preload.ts'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  target: 'electron-preload',
  externals: {
    'electron': 'commonjs electron',
  },
  optimization: {
    ...commonConfig.optimization,
    sideEffects: false
  }
};

// 开发环境渲染进程配置（使用web target）
const rendererDevConfig = {
  ...commonConfig,
  mode: 'development',
  entry: {
    renderer: ['./src/frontend/renderer.tsx']
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    ...commonConfig.resolve,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      chunks: ['renderer']
    }),
    // 确保 global 对象在渲染进程中可用
    new webpack.BannerPlugin({
      banner: '(function() { window.global = window; })();',
      raw: true,
      entryOnly: false
    }),
  ],
  // 开发环境使用web target
  target: 'web',
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 9000,
    hot: true,
    liveReload: true,
    historyApiFallback: true,
    client: {
      overlay: {
        errors: true,
        warnings: false
      },
      progress: true,
      reconnect: 5
    },
    watchFiles: ['src/frontend/**/*', 'public/**/*']
  },
  optimization: {
    ...commonConfig.optimization,
    sideEffects: false
  },
};

// 生产环境渲染进程配置（使用electron-renderer target）
const rendererProdConfig = {
  ...commonConfig,
  mode: 'production',
  entry: {
    renderer: ['./src/frontend/renderer.tsx']
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    ...commonConfig.resolve,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: 'index.html',
      chunks: ['renderer']
    }),
    // 确保 global 对象在渲染进程中可用
    new webpack.BannerPlugin({
      banner: '(function() { window.global = window; })();',
      raw: true,
      entryOnly: false
    }),
  ],
  // 生产环境使用electron-renderer target
  target: 'electron-renderer',
  externals: {
    'electron': 'commonjs electron',
  },
  optimization: {
    ...commonConfig.optimization,
    minimize: true, // 生产环境启用代码压缩
    sideEffects: false
  },
};

// 根据环境选择正确的渲染进程配置
const rendererConfig = mode === 'development' ? rendererDevConfig : rendererProdConfig;

module.exports = [mainConfig, preloadConfig, rendererConfig];